package fit.deni.pages;

import java.util.LinkedList;
import java.util.List;

import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.BeanEditForm;
import org.apache.tapestry5.ioc.annotations.Inject;

import fit.deni.beans.Klub;
import fit.deni.beans.Zaposleni;
import fit.deni.hibernate.interfaces.KlubService;
import fit.deni.hibernate.interfaces.ZaposleniService;
import fit.deni.utils.Utils;

public class Register {
	
	@Property
	private Zaposleni noviZaposleni;
	
	@Property
	private String selectRole = "Korisnik", password, passwordAgain;
	
	@Property
	private Klub selectedClub;
	
	@Component
	private BeanEditForm registerForm;
	
	@Inject
	private ZaposleniService zaposleniService;
	
	@Property
	private ValueEncoder<Klub> encoderClub = new ValueEncoder<Klub>() {
		public String toClient(Klub value) {
			return value.getIme();
		}
		public Klub toValue(String clientValue) {
			return klubService.getClubByName(clientValue);
		}
	};
	
	public List<Klub> getAllClubs() {
		return new LinkedList<Klub>(klubService.getAll());
	}
	
	@Inject
	private KlubService klubService;
	
	private Object onSuccess() {
		if(selectRole.equals("Administrator")) noviZaposleni.setRole(Zaposleni.ADMINISTRATOR);
		else noviZaposleni.setRole(Zaposleni.USER);
		if(password.equals(passwordAgain)) {
			noviZaposleni.setPasswordHash(Utils.getHashOf(password));
		}
		else {
			registerForm.recordError("Lozinke se ne poklapaju, pokusajte ponovo");
			return null;
		}
		zaposleniService.addUser(noviZaposleni);
		noviZaposleni = new Zaposleni();
		return Login.class;
	}
	
	@SessionState
	private Zaposleni korisnik;
	private boolean korisnikExists;
	
	public boolean isAdminLoged() {
		if(!korisnikExists) return false;
		return korisnik.getRole()==Zaposleni.ADMINISTRATOR;
	}

}
